package com.common.ajax.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import com.caits.lbs.framework.Constants;
import com.caits.lbs.framework.log.CommonLogFactory;
import com.caits.lbs.framework.utils.SpringUtils;
import com.caits.lbs.framework.utils.Dom4jXmlUtil;

/**
 * <p>
 * XMLPost
 * </p>
 * <p>
 * xml post方式接收请求，发起IRequest调用，在返回给页面
 * </p>
 * 
 * @author 周华彬(zhouhuabin@ctfo.com, zhou_hua_bin@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">版本号</th>
 *          <th width="100px">动作</th>
 *          <th width="100px">修改人</th>
 *          <th width="100px">修改时间</th>
 *          </tr>
 *          <!-- 以 Table 方式书写修改历史 -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td>创建类</td>
 *          <td>zhb</td>
 *          <td>2011-4-2 下午03:04:31</td>
 *          </tr>
 *          <tr>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          <td>XXX</td>
 *          </tr>
 *          </table>
 */
public class CommonXMLServet extends HttpServlet {
	/** TODO */
	private static final long serialVersionUID = 1L;
	private static final String REQUEST_ENCODING = "UTF-8";
	private static final String CONTENT_TYPE_XML = "text/xml; charset=UTF-8";
	private static final String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";
	
	/** log writer */
	protected static Logger log = CommonLogFactory.getLog();

	/** 系统常量类 */
	protected Constants constant;

	private SAXReader builder = new SAXReader(); 
	
	// Initialize global variables
	public void init() throws ServletException {
		constant = (Constants) SpringUtils.getBean("constant");
		

	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(REQUEST_ENCODING);
		String xml = request.getParameter("xml");
		String callback = request.getParameter("callback");
		// clear cache
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "Tue, 01 Jan 1980 1:00:00 GMT");
		if ((xml == null) || (xml.length() <= 0)) {
			response.setContentType(CONTENT_TYPE_HTML);
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
			out.println("<title>error</title>");
			out.println("</head>");
			out.println("<body bgcolor=\"#ffffff\">");
			out.println("error<br/>");
			out.println("keyword xml not found");
			out.println("</html>");
			out.close();
			return;
		}
		boolean isHTML = ((callback != null) && (callback.length() > 0));
		Document requestDoc = null;
		try {
			requestDoc = Dom4jXmlUtil.StringTodocument(xml);
		} catch (Exception ex) {
			log.error("HTTP.doGet:" + ex.getMessage(),ex);
			if (isHTML) {
				response.setContentType(CONTENT_TYPE_HTML);
				PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<head>");
				out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
				out.println("<title>error</title>");
				out.println("</head>");
				out.println("<body bgcolor=\"#ffffff\">");
				out.println("error<br/>");
				out.println("xml parser error");
				out.println("</html>");
				out.close();
			} else {
				response.setContentType(CONTENT_TYPE_XML);
				PrintWriter out = response.getWriter();
				out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
				out.println("<response Result=\"-100\">");
				out.println("<error>xml parser error</error>");
				out.println("</response>");
				out.close();
			}
			return;
		}

		Document responseDoc = null;
		responseDoc = RequestParser.parse(requestDoc,RequestLocalParser.getSession(request));
		if (isHTML) {
			response.setContentType(CONTENT_TYPE_HTML);
			// response.sendRedirect("")
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
			out.println("<title>__response</title>");
			out.println("</head>");
			out.println("<body bgcolor=\"#ffffff\">");
			out.println("<SCRIPT LANGUAGE=javascript>");
			// 转义
			// " -> \"
			// \r - > \r
			// \n -> \n
			String resString = Dom4jXmlUtil.documentToString(responseDoc);
			resString = resString.replaceAll("\"", "\\\\\"");
			resString = resString.replaceAll("\r", "\\\\r");
			resString = resString.replaceAll("\n", "\\\\n");
			// System.out.println("out:"+resString);
			out.println("    var xmlData = \"" + resString + "\";");
			out.println("    " + callback + "(xmlData);");
			out.println("</SCRIPT>");
			out.println("</body>");
			out.println("</html>");
			out.close();
		} else {
			response.setContentType(CONTENT_TYPE_XML);
			PrintWriter out = response.getWriter();
			// 输出
			out.println(responseDoc.asXML());
			out.close();
		}
	}

	// Process the HTTP Post request
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
		response.setContentType(CONTENT_TYPE_XML);
		request.setCharacterEncoding(REQUEST_ENCODING);
		PrintWriter out = response.getWriter();

		BufferedReader bufReader = request.getReader();
		Document requestDoc = null;
		try {
			requestDoc = builder.read(bufReader);
			log.info("收到请求xml:\r\n" + Dom4jXmlUtil.documentToString(requestDoc));
		} catch (Exception ex) {
			out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
			out.println("<response Result=\"-100\">");
			out.println("<error>xml parser error</error>");
			out.println("</response>");
			out.close();
			return;
		}
		Document responseDoc = null;
		String resString = null;
		responseDoc = RequestParser.parse(requestDoc,RequestLocalParser.getSession(request));
		
		if (responseDoc == null) {
			resString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
			resString += "<response Result=\"-101\">";
			resString += "<error>xml dealt error</error>";
			resString += "</response>";
		} else
			resString = Dom4jXmlUtil.documentToString(responseDoc);
		out.println(resString);
		out.close();
		log.info("返回响应xml:\r\n" + resString);
	}

	// Clean up resources
	public void destroy() {
	}


}
